package com.travel.lib.base.retrofit;


import com.travel.lib.base.constantdata.Constants;
import com.travel.lib.base.constantdata.NetConstants;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by spc on 2017/4/26.
 */

public class RetrofitUtils {

    //api接口的
    private static class RetrofitAPIHolder {
        private static Retrofit retrofit = createAPIRetrofit();
        private final static int CONNECT_TIMEOUT = 20;
        private final static int READ_TIMEOUT = 20;
        private final static int WRITE_TIMEOUT = 20;

        private static Retrofit createAPIRetrofit() {
            OkHttpClient httpclint;
            if (!Constants.RELEASE_CLIENT) {
                httpclint = new OkHttpClient.Builder()
                        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                        .addInterceptor(new AutoInterceptor())
                        .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                        .build();
            } else {
                httpclint = new OkHttpClient.Builder()
                        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                        .addInterceptor(new AutoInterceptor())
                        .build();

            }
            return new Retrofit.Builder()
                    .client(httpclint)
                    .baseUrl(NetConstants.getServerUrl())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }
    }

    public static Retrofit getAPIInstance() {
        return RetrofitAPIHolder.retrofit;
    }


    public static RequestBody ceeateBody(String json) {
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), json);
        return body;
    }
}

